/**
 * JAVACC DEMO 1.0
 */
package com.apache.passport.service.plugins;

import com.apache.api.manager.PluginConnector;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.cache.util.Validator;
import com.apache.database.constant.SystemTools;
import com.apache.passport.common.PassportHelper;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/**
 * description:  发送邮件
 *
 * @author Hou Dayu 创建时间：2016-12-22
 */
public class SendEmailPlugin implements PluginConnector {

    private static final String DEFAULT_ENCODING = "UTF-8";

    private JavaMailSenderImpl mailSender;

    private Template template;

    /**
     * description: 发送邮件
     *
     * @param userEmail
     */
    public boolean sendNotificationMail(String userEmail, String randNum) {
        boolean flag = false;
        String formEmail = SystemTools.getInstance().getValue("mail.username");
        String password = SystemTools.getInstance().getValue("mail.password");
        String protocol = SystemTools.getInstance().getValue("mail.transport.protocol");
        String host = SystemTools.getInstance().getValue("mail.host");
        String port = SystemTools.getInstance().getValue("mail.port");
        String subject = SystemTools.getInstance()
                .getValue("mail.subject");//.getValue("mail.subject");
        try {
            mailSender.setDefaultEncoding(DEFAULT_ENCODING);
            mailSender.setHost(host);
            mailSender.setPassword(password);
            mailSender.setPort(Integer.parseInt(port));
            mailSender.setProtocol(protocol);
            mailSender.setUsername(formEmail);

            MimeMessage msg = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(msg, true, DEFAULT_ENCODING);
            //生成邮件内容.
            String content = generateContent(userEmail, randNum);
            helper.setFrom(formEmail);
            helper.setTo(userEmail);
            helper.setSubject(subject);
            helper.setText(content, true);
            mailSender.send(msg);
            flag = true;
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * description:  通过ftl组装发送报文
     *
     * @return
     */
    private String generateContent(String userEmail, String randNum) {
        String sndRtn = "";
        try {
            String nowTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            Map<String, String> context = new HashMap<String, String>();
            context.put("userEmail", userEmail);
            context.put("verCode", randNum);
            context.put("nowTime", nowTime);
            sndRtn = FreeMarkerTemplateUtils.processTemplateIntoString(template, context);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
        return sndRtn;
    }

    /**
     * description:  获取classpath中的附件.
     *
     * @param attPath
     * @return
     */
    @SuppressWarnings("unused")
    private File generateAttachment(final String attPath) {
        File file = null;
        try {
            Resource resource = new ClassPathResource(attPath);
            file = resource.getFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }

    /**
     * TODO 简单描述该方法的实现功能（可选）.
     *
     * @see com.apache.api.manager.PluginConnector#execute(com.apache.api.vo.ParamsVo)
     */
    @Override
    public Object execute(ParamsVo vo) throws Exception {
        ResultEntity result = new ResultEntity();
        result.setResult("true");
        result.setMessage("发送失败");
        result.setEntity("F");
        String userEmail = (String) vo.getParams("userEmail");
        String randNum = PassportHelper.getInstance().createRandomString(6);
        boolean flag = sendNotificationMail(userEmail, randNum);
        if (flag) {
            result.setMessage("发送成功");
            result.setEntity(randNum);
        }
        return result;
    }

    public void setMailSender(JavaMailSenderImpl mailSender) {
        this.mailSender = mailSender;
    }

    public void setFreemarkerConfiguration(Configuration freemarkerConfiguration)
            throws IOException {
        //template = freemarkerConfiguration.getTemplate("ftl/mailTemplate.ftl", DEFAULT_ENCODING);
    }

    /**
     * 获取freemarker的配置. freemarker本身支持classpath,目录和从ServletContext获取.
     */
    private void getFreeMarkerCFG() {
        File templateFile = new File(Validator.getClassLoaderPath() + "ftl");
        Configuration freemarker_cfg = new Configuration();
        try {
            freemarker_cfg.setDirectoryForTemplateLoading(templateFile);
            freemarker_cfg.setEncoding(Locale.CHINA, "UTF-8");
            template = freemarker_cfg.getTemplate("mailTemplate.ftl", DEFAULT_ENCODING);
        } catch (IOException e) {
        }
    }
}
